package com.example;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

// 测试Java的零拷贝技术
public class ZeroCopyTests {

    public static void main(String[] args) throws IOException {
        // 打开文件
        RandomAccessFile file = new RandomAccessFile("/tmp/test.txt", "r");
        FileChannel channel = file.getChannel();

        // 映射文件到内存，整个文件
        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

        // 读取数据
        while (buffer.hasRemaining()) {
            // 假设我们知道我们正在读取文本数据
            System.out.print((char) buffer.get());
        }

        // 关闭通道
        channel.close();
    }
}
